<?php
namespace App\Libs\platformApi;
use Illuminate\Support\Facades\DB;
// lazada SDK
require_once (app_path().'/Libs/lazada/Autoloader.php');
class Lazada{
/////////////////////////////////////////////// lazada api
	
	public $app_key;                //客户id
	public $app_secret;           //秘钥
	public $refresh_token;      //刷新令牌
	public $access_token;      //访问令牌
	public $shop_id;          //店铺id
	
	/*
	 *  初始化
	 * @param app_key 客户id
	 * @param app_secret 秘钥
	 * @param refresh_token 刷新令牌
	 * @param access_token 访问令牌
	 * @parma shop_id 店铺id
	 * */
	public function __construct($data=array())
	{
		$this->app_key = empty($data['app_key']) ? '100498' : $data['app_key'];
		$this->app_secret = empty($data['app_secret']) ? 'KIgUMBZzQB53Xp73D5X5TFbFYIz0WHce' : $data['app_secret'];
		$this->refresh_token = empty($data['refresh_token']) ? '' : $data['refresh_token'];
		$this->access_token = empty($data['access_token']) ? '' : $data['access_token'];
		$this->shop_id = empty($data['shop_id']) ? '' : $data['shop_id'];
	}
	
    /*
     * 获取平台品牌
     * */
    public function brand_get($data){
        $url = 'https://api.lazada.com.my/rest';
        $lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
        $request = new \LazopRequest('/category/brands/query');
        $request->addApiParam('startRow','0');
        $request->addApiParam('pageSize','200');
        $res = $lazada->execute($request, $this->access_token);
        $resData = json_decode($res, true);
        return $resData;
    }
	
	/*
	 * 获取平台分类
	 * */
	public function category_get(){
		$url = 'https://api.lazada.com.my/rest';
		$lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
		$request = new \LazopRequest('/category/tree/get', 'GET');
		$res = $lazada->execute($request, $this->access_token);
		$res = json_decode($res, true);
		if ($res['code'] != '0') {
			$is_overdue_token = strstr($res['message'], 'access token');
			if (!$is_overdue_token) {
				return $res;//$res
			}
			
			//This access token has been revoked ：此访问令牌已被吊销
			// 刷新 access_token
			$refresh_token = $this->refresh_token();
			if ($refresh_token !== true) {
				return $refresh_token;
			}
			
			// 重新调用
			$res = $lazada->execute($request, $this->access_token);
			$res = json_decode($res, true);
		}
		
		return $res;
	}


 
	/*
	 * 上传产品
	 * */
	public function product_add($data){
	    //var_dump($data);die;
		$arr = array();
		$Product['PrimaryCategory'] = $data['spu']['primary_category'];// 产品类别id
		$Product['SPUId'] = !empty($data['spu']['SPUId']) ? $data['spu']['SPUId'] : '';// SPU的ID  可选
		$Product['AssociatedSku'] = !empty($data['spu']['AssociatedSku']) ? $data['spu']['AssociatedSku'] : '';// 关联产品sku  可选
		$Product['Attributes'] = array();// 产品属性
		$Product['Attributes']['name'] = $data['spu']['name'];// 产品名称
		$Product['Attributes']['description'] = "'{$data['spu']['description']}'";// 产品介绍
		$Product['Attributes']['short_description'] = "'{$data['spu']['short_description']}'";// 产品简介
		$Product['Attributes']['description'] = 'test';// 产品介绍
		$Product['Attributes']['short_description'] = 'test';// 产品简介
		$Product['Attributes']['brand'] = !empty($data['spu']['brand']) ? $data['spu']['brand'] : 'NO Brand';// 产品品牌
		$Product['Attributes']['model'] = $data['spu']['model'];// 产品型号  可选
		$Product['Attributes']['warranty'] = !empty($data['spu']['warranty']) ? $data['spu']['warranty'] : '';// 产品的保修时间  可选
		$Product['Attributes']['warranty_type'] = !empty($data['spu']['warranty_type']) ? $data['spu']['warranty_type'] : '';// 产品的保修类型  可选
		//var_dump($data);die;
		$Product['Skus'] = array();// sku
		foreach ($data['sku'] as $k=>$v){
			$sku = array();
			$sku['SellerSku'] = $v['seller_sku'];// sku
			$sku['color_family'] = $v['color_family'];// 颜色
			$sku['size'] = $v['size'];// 尺码
			$sku['price'] = $v['price'];// 产品价格
			$sku['quantity'] = $v['quantity'];// 库存
			$sku['package_height'] = $v['package_height'];// 包装高度
			$sku['package_length'] = $v['package_length'];// 包装长度
			$sku['package_width'] = $v['package_width'];// 包装宽度
			$sku['package_weight'] = $v['package_weight'];// 包裹重量
			//$sku['package_weight'] = $v['package_weight'];// 包裹重量
			$sku['package_content'] = $data['spu']['package_content'];// 包装内容  可选
            if(isset($v['special_price'])){
                $sku['special_price'] = $v['special_price'];// 特价 可选
            }
            if(isset($v['special_time'][0])){
                $sku['special_from_date'] = $v['special_time'][0];// 特价开始时间 可选
            }
            if(isset($v['special_time'])){
                $sku['special_to_date'] = $v['special_time'][1];// 特价开始时间 可选
            }

			$sku['Images'] = array();// 图片  可选
			foreach ($v['image'] as $k1=>$v1){
				$sku["Images"]["Image[{$k1}]"] = $v1;
			}
			
			$Product["Skus"]["Sku[{$k}]"] = $sku;
		}
//		return $Product;
		$arr['Request']['Product'] = $Product;
		$data_xml = $this->xml_encode($arr);
//		return $data_xml;
		
		if($data['country'] == 'Philippines'){
			$url = 'https://api.lazada.com.ph/rest';//菲律宾
		}else if($data['country'] == 'Thailand'){
			$url = 'https://api.lazada.co.th/rest';//泰国
		}else if($data['country'] == 'Singapore'){
			$url = 'https://api.lazada.sg/rest';//新加坡
		}else if($data['country'] == 'Malaysia'){
			$url = 'https://api.lazada.com.my/rest';//马来西亚
		}else if($data['country'] == 'Vietnam'){
			$url = 'https://api.lazada.vn/rest';//越南
		}else if($data['country'] == 'Indonesia'){
			$url = 'https://api.lazada.co.id/rest';//印度尼西亚
		}
		
		$lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
		$request = new \LazopRequest('/product/create');
		$request->addApiParam('payload',$data_xml);
		$res = $lazada->execute($request, $this->access_token);
		$res = json_decode($res, true);
		if ($res['code'] != '0') {
			$is_overdue_token = strstr($res['message'], 'access token');
			if (!$is_overdue_token) {
				return $res;//$res
			}
			
			//This access token has been revoked ：此访问令牌已被吊销
			// 刷新 access_token
			$refresh_token = $this->refresh_token();
//			return $refresh_token;
			if ($refresh_token !== true) {
				return $refresh_token;
			}
			
			// 重新调用
			$res = $lazada->execute($request, $this->access_token);
			$res = json_decode($res, true);
		}
		
		return $res;
	}
	
	/**
	 * XML编码
	 * @param mixed $data 数据
	 * @param string $encoding 数据编码
	 * @return string
	 */
	public function xml_encode($data, $root=true, $encoding='utf-8'){
		$xml="";
		if($root){
			$xml .= '<?xml version="1.0" encoding="' . $encoding . '"?>';
		}
		foreach($data as $key => $val){
			//去掉key中的下标[]
			$key = preg_replace('/\[\d*\]/', '', $key);
			if(is_array($val)){
				$child = $this->xml_encode($val, false);
				$xml .= "<$key>$child</$key>";
			}else{
				$xml.= "<$key>$val</$key>";
			}
		}
		return $xml;
	}
	
	/**
	 * 获取商品信息
	 * @param access_token
	 * @parma filter   状态  all、live、inactive、deleted、image missing、pending、rejected、sell out
	 * @param update_after 更新时间之后
	 * @param update_before 更新时间之前
	 * @param offset 偏移数
	 * @param limit 每页条数
	 */
	public function product_get($data){
		if(empty($data)){
			return '接收值为空';
		}
		
		//// 获取商品
		$update_after = gmdate('Y-m-d\TH:i:s', strtotime($data['time_start']));//开始时间
//		$update_after = '2021-02-20T04:40:16';//开始时间
		$update_before = gmdate('Y-m-d\TH:i:s', strtotime($data['time_end']));//结束时间
		$offset = ($data['page'] - 1) * $data['limit'];
		$limit = $data['limit'];
		
		$url = 'https://api.lazada.com.my/rest';
		$lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
		$request = new \LazopRequest('/products/get','GET');
		$request->addApiParam('filter', 'all');//
		$request->addApiParam('update_after', $update_after);// 开始时间
		$request->addApiParam('update_before', $update_before);// 结束时间
		$request->addApiParam('offset', $offset);// 偏移
		$request->addApiParam('limit', $limit);// 每页条数
//		$request->addApiParam('options', '1');
		
		$res_data = $lazada->execute($request, $this->access_token);//返回json
		$res_data = json_decode($res_data,true);
		if ($res_data['code'] != '0') {
			$is_overdue_token = strstr($res_data['message'], 'access token');
			if (!$is_overdue_token) {
				return $res_data;
			}
			
			//This access token has been revoked ：此访问令牌已被吊销
			// 刷新 access_token
			$refresh_token = $this->refresh_token();
			if ($refresh_token !== true) {
				return $refresh_token;
			}
			
			// 重新调用
			$res_data = $lazada->execute($request, $this->access_token);
			$res_data = json_decode($res_data, true);
		}
		return $res_data;
	}
	
	/**
	 * 获取 access_token
	 * 说明：code
	 * */
	public function access_token_get($data){
		if(empty($data['code'])){
			return 'code为空';
		}
		
		$url = 'https://auth.lazada.com/rest';
		$lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
		$request = new \LazopRequest('/auth/token/create');
		$request->addApiParam('code', $data['code']);
		//$request->addApiParam('uuid','38284839234');
		$resData = $lazada->execute($request);//die;
		$resData = json_decode($resData,true);
		
		if($resData['code'] == 0){
			$resData['app_key'] = $this->app_key;
			$resData['app_secret'] = $this->app_secret;
		}
		return $resData;
	}
	
	/*
	 * 刷新 access_token
	 * @param shop_id 店铺id
	 * @param app_key
	 * @param app_secret 秘钥
	 * @param refresh_token 获取access_token（上个接口获取到的数据）
	 * */
	public function refresh_token(){
		$url = 'https://api.lazada.com/rest';
		$lazada = new \LazopClient($url, $this->app_key, $this->app_secret);
		$request = new \LazopRequest('/auth/token/refresh');
		$request->addApiParam('refresh_token', $this->refresh_token);
		
		$res_data = $lazada->execute($request);//返回json
		$res_data = json_decode($res_data, true);
		if($res_data['code'] != 0){
			return $res_data;
		}
		
		//// 更新access_token
		$sql = "update shop
					set access_token='{$res_data['access_token']}'
					where `Id` = {$this->shop_id}";
		$update = db::update($sql);
		
		$this->access_token = $res_data['access_token'];
		return true;
	}
	
	
	/**
	 * 毫秒转日期
	 */
	public function time_hm($msectime)
	{
		$msectime = $msectime * 0.001;
		if(strstr($msectime,'.')){
			sprintf("%01.3f",$msectime);
			list($usec, $sec) = explode(".",$msectime);
			$sec = str_pad($sec,3,"0",STR_PAD_RIGHT);
		}else{
			$usec = $msectime;
			$sec = "000";
		}
		$date = date("Y-m-d H:i:s",$usec);
//		$mescdate = str_replace('x', $sec, $date);
		return $date;
	}
	
	//编辑spu
	public function updateSpuProduct($accessToken, $itemId, $name, $desc, $sellerSku){
        $xml = <<<eof
<Request>     
 <Product>     
  <ItemId>$itemId</ItemId>         
  <Attributes>             
   <name>$name</name>             
   <short_description>$desc</short_description>                    
  </Attributes>         
  <Skus>             
   <Sku>                
    <SellerSku>$sellerSku</SellerSku>                      
   </Sku>                   
  </Skus>     
 </Product> 
</Request>
eof;
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,'100498','KIgUMBZzQB53Xp73D5X5TFbFYIz0WHce');
        $request = new \LazopRequest('/product/update');
        $request->addApiParam('payload',$xml);
        $res = $c->execute($request, $accessToken);
        return json_decode($res,true);
    }

    //编辑sku
    public function updateSkuProduct($accessToken, $itemId, $sellerSku, $quantity, $price, $image){
	    $str = '';
	    foreach ($image as $v) {
	        $str .= "<Image>".$v."</Image>";
        }
        $str = "<Images>$str</Images>";
        $xml = <<<eof
<Request>     
 <Product>     
  <ItemId>$itemId</ItemId>                
  <Skus>             
   <Sku>                
    <SellerSku>$sellerSku</SellerSku>           
    <quantity>$quantity</quantity>                 
    <price>$price</price>                                             
    $str           
   </Sku>                   
  </Skus>     
 </Product> 
</Request>
eof;
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,'100498','KIgUMBZzQB53Xp73D5X5TFbFYIz0WHce');
        $request = new \LazopRequest('/product/update');
        $request->addApiParam('payload',$xml);
        $res = $c->execute($request, $accessToken);
        return json_decode($res,true);
    }

    public function uploadImage($accessToken, $image){
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,'100498','KIgUMBZzQB53Xp73D5X5TFbFYIz0WHce');
        $request = new \LazopRequest('/image/upload');
        $request->addFileParam('image',file_get_contents($image));
        return json_decode($c->execute($request, $accessToken),true);
    }

    public function setStatusPacked($accessToken){
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,$this->app_key,$this->app_secret);
        $request = new \LazopRequest('/order/pack');
        $request->addApiParam('shipping_provider','LGS-FM48');
        $request->addApiParam('delivery_type','dropship');
        $request->addApiParam('order_item_ids','[243662241652980]');
        $res = $c->execute($request, $accessToken);
        return json_decode($res,true);
    }

    public function setStatusRts($accessToken){
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,$this->app_key,$this->app_secret);
        $request = new \LazopRequest('/order/rts');
        $request->addApiParam('delivery_type','dropship');
        $request->addApiParam('order_item_ids','[243662241652980]');
        $request->addApiParam('shipment_provider','Aramax');
        $request->addApiParam('tracking_number','12345678');
        $res = $c->execute($request, '50000901d41uq9YccwdmyxljlLGYdwynlXDxteOQzxrtwVDTivl6R1ba1d561jr');
        return json_decode($res,true);
    }

    //新增sku
    public function addSku($accessToken, $categoryId, $otherSku, $sellerSku, $quantity, $price, $image, $color, $size
                            ,$packageLength, $packageHeight, $packageWeight, $packageWidth){
        $str = '';
        foreach ($image as $v) {
            $str .= "<Image>".$v."</Image>";
        }
        $str = "<Images>$str</Images>";
        //非跨境
        $xml = <<<eof
<?xml version="1.0" encoding="UTF-8"?>
<Request>     
 <Product>     
  <PrimaryCategory>$categoryId</PrimaryCategory>         
  <AssociatedSku>$otherSku</AssociatedSku>                        
  <Skus>             
   <Sku>                 
    <SellerSku>$sellerSku</SellerSku>                          
    <quantity>$quantity</quantity>                 
    <price>$price</price> 
    <color_family>$color</color_family>
    <size>$size</size>         
    <package_length>$packageLength</package_length>                 
    <package_height>$packageHeight</package_height>                 
    <package_weight>$packageWeight</package_weight>                 
    <package_width>$packageWidth</package_width>                                     
    $str           
   </Sku>        
  </Skus>     
 </Product> 
</Request>
eof;
        $url = 'https://api.lazada.com.my/rest';
        $c = new \LazopClient($url,'113943','9J0bUe2UEZSfhSMdZBkLXgtWgSRSX0VC');
        $request = new \LazopRequest('/product/create');
        $request->addApiParam('payload',$xml);
        $res = $c->execute($request, $accessToken);
        return json_decode($res,true);
    }
	
	
	
	
	
	
	
	
	
	
	
	
}
?>